"""
定义基础类，负责创建driver
"""
from appium import webdriver
import os


class BaseDriver:
    DRIVER = None
    def __init__(self):
        caps = {}
        caps["automationName"] = "UiAutomator2"
        caps["platformName"] = "Android"
        # caps["deviceName"] = "127.0.0.1:21503"  # 使用自己的手机devices name
        # udid 作为手机设备的唯一配置项
        if os.getenv('device'):
            caps['udid'] = os.getenv('device')
        caps['noReset'] = False  # 登录状态清空
        caps['fullReset'] = False
        caps['appPackage'] = "org.cnodejs.android.md"
        caps['appActivity'] = ".ui.activity.LaunchActivity"
        # 当第二次被实例化的时候，保证driver 唯一
        if BaseDriver.DRIVER == None:
            self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_capabilities=caps)
            BaseDriver.DRIVER = self.driver
        # 保证同一个driver 都为一个driver
        self.driver = BaseDriver.DRIVER
        self.driver.implicitly_wait(10)
        self.android_uiautomator = 'new UiSelector().'

    def swipe_by_custorm(self,dirction):
        windowsize = self.driver.get_window_rect()
        # print(windowsize)
        width = windowsize['width']
        height = windowsize['height']
        if dirction == 'left':
            # 从左往右滑动
            self.driver.swipe(start_x=1,start_y=height/2,end_x=width-1,end_y=height/2)
        elif dirction == 'right':
            # 从右往左滑动
            self.driver.swipe(start_x=width-1,start_y=height/2,end_x=1,end_y=height/2)
        elif dirction == 'up':
            # 从下往上滑动
            self.driver.swipe(start_x=1,start_y=height/2,end_x=1,end_y=1)
        elif dirction == 'down':
            # 从上往下滑动
            self.driver.swipe(start_x=1,start_y=1,end_x=1,end_y=height/2)


    def get_toast_text(self):
        return self.driver.find_element_by_xpath('//android.widget.Toast').text

    @staticmethod
    def back_to_main_page():
        while True:
            ct = BaseDriver.DRIVER.current_activity
            # 如果已经返回到首页
            if ".ui.activity.MainActivity" in ct:
                break
            BaseDriver.DRIVER.back()

    @staticmethod
    def save_screenshots(pngfile):
        BaseDriver.DRIVER.save_screenshot(pngfile)

    @staticmethod
    def closeDriver():
        BaseDriver.DRIVER.quit()
        print('Now Driver value is ',BaseDriver.DRIVER)
        BaseDriver.DRIVER = None

if __name__ == '__main__':
    bd = BaseDriver()
